<template>
  <div class="audit-page">
    <!-- 顶部导航栏 -->
    <el-header class="header">
      <div class="logo">校园失物招领平台 - 审核管理</div>
      <div class="user-info">
        <el-avatar size="small" icon="el-icon-user"></el-avatar>
        <span>管理员</span>
        <el-dropdown @command="handleCommand">
          <i class="el-icon-setting" style="margin-left: 15px;"></i>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="logout">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </el-header>

    <!-- 主内容区 -->
    <div class="content-wrapper">
      <!-- 面包屑导航 -->
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>信息审核</el-breadcrumb-item>
      </el-breadcrumb>

      <!-- 页面标题 -->
      <h3 class="page-title">失物招领信息审核</h3>

      <!-- 选项卡切换 -->
      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <el-tab-pane label="失物信息审核" name="lost"></el-tab-pane>
        <el-tab-pane label="招领信息审核" name="found"></el-tab-pane>
      </el-tabs>

      <!-- 表格工具栏 -->
      <div class="table-toolbar">
        <el-button type="success" icon="el-icon-check" @click="handleBatchPass" 
          :disabled="getSelectedRows.length === 0">
          批量通过
        </el-button>
        <el-button type="danger" icon="el-icon-close" @click="handleBatchReject" 
          :disabled="getSelectedRows.length === 0">
          批量驳回
        </el-button>
        <el-button type="warning" icon="el-icon-refresh" @click="fetchCurrentData">
          刷新
        </el-button>
      </div>

      <!-- 数据表格区域 -->
      <el-table
        :data="getCurrentTableData"
        border
        stripe
        highlight-current-row
        style="width: 100%; margin-top: 16px;"
        @selection-change="handleSelectionChange"
        :loading="getCurrentLoading"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="userId" label="用户ID" width="100" align="center" />
        <el-table-column prop="title" label="物品名称" align="center" />
        <el-table-column label="物品类别" align="center" width="120">
          <template #default="scope">
            {{ getCategoryName(scope.row.categoryId) }}
          </template>
        </el-table-column>
        <el-table-column label="图片" align="center" width="100">
          <template #default="scope">
            <el-image
              v-if="scope.row.images && scope.row.images.length > 0"
              :src="scope.row.images[0].url"
              :preview-src-list="scope.row.images.map(img => img.url)"
              style="width: 60px; height: 60px; object-fit: cover"
            />
            <el-empty v-else size="small" description="无图片" />
          </template>
        </el-table-column>
        <el-table-column :label="currentTabTimeLabel" align="center">
          <template #default="scope">
            {{ formatDateTime(getCurrentTabTime(scope.row)) }}
          </template>
        </el-table-column>
        <el-table-column :label="currentTabLocationLabel" align="center">
          <template #default="scope">
            {{ getCurrentTabLocation(scope.row) }}
          </template>
        </el-table-column>
        <el-table-column prop="contactWay" label="联系方式" align="center" />
        <el-table-column prop="status" label="审核状态" align="center">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="180">
          <template #default="scope">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-view"
              @click="() => showItemDetail(scope.row)"
            >详情</el-button>
            <el-button
              type="success"
              size="mini"
              icon="el-icon-check"
              @click="() => handlePass(scope.row)"
              v-if="scope.row.status === 1"
            >通过</el-button>
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-close"
              @click="() => handleReject(scope.row)"
              v-if="scope.row.status === 1"
            >驳回</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="getCurrentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="getCurrentPageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="getCurrentTotal"
        style="margin-top: 16px; text-align: center;"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import Swal from 'sweetalert2'
import 'sweetalert2/dist/sweetalert2.min.css'

// API配置
const API_BASE_URL = 'http://172.20.10.2:8080/api'

// 状态管理 - 完全分离失物和招领数据
const lostLoading = ref(false)
const foundLoading = ref(false)
const activeTab = ref('lost') // 默认显示失物信息

// 失物数据
const lostTableData = ref([])
const lostTotal = ref(0)
const lostCurrentPage = ref(1)
const lostPageSize = ref(10)
const lostSelectedRows = ref([])

// 招领数据
const foundTableData = ref([])
const foundTotal = ref(0)
const foundCurrentPage = ref(1)
const foundPageSize = ref(10)
const foundSelectedRows = ref([])

// 分类数据
const categoryList = ref([])

// 审核状态映射 (1:待审核, 2:已通过, 3:已驳回, 4:已完成)
const auditStatusMap = {
  1: { text: '待审核', type: 'info' },
  2: { text: '已通过', type: 'success' },
  5: { text: '已驳回', type: 'danger' },
  4: { text: '已完成', type: 'primary' }
}

// 当前选项卡的时间标签
const currentTabTimeLabel = computed(() => {
  return activeTab.value === 'lost' ? '丢失时间' : '捡到时间'
})

// 当前选项卡的地点标签
const currentTabLocationLabel = computed(() => {
  return activeTab.value === 'lost' ? '丢失地点' : '捡到地点'
})

// 计算属性 - 获取当前类型数据
const getCurrentTableData = computed(() => {
  return activeTab.value === 'lost' ? lostTableData.value : foundTableData.value
})

const getCurrentLoading = computed(() => {
  return activeTab.value === 'lost' ? lostLoading.value : foundLoading.value
})

const getCurrentPage = computed(() => {
  return activeTab.value === 'lost' ? lostCurrentPage.value : foundCurrentPage.value
})

const getCurrentPageSize = computed(() => {
  return activeTab.value === 'lost' ? lostPageSize.value : foundPageSize.value
})

const getCurrentTotal = computed(() => {
  return activeTab.value === 'lost' ? lostTotal.value : foundTotal.value
})

const getSelectedRows = computed(() => {
  return activeTab.value === 'lost' ? lostSelectedRows.value : foundSelectedRows.value
})

// 页面加载时获取数据
onMounted(() => {
  fetchCategoryList()
  fetchCurrentData()
})

// 获取分类列表
const fetchCategoryList = async () => {
  try {
    const response = await axios.get(`${API_BASE_URL}/Category/getAll`)
    if (response.data.code === 200) {
      categoryList.value = response.data.data || []
    } else {
      ElMessage.error(response.data.message || '获取分类列表失败')
    }
  } catch (error) {
    console.error('获取分类列表失败', error)
    ElMessage.error('网络错误，请稍后再试')
  }
}

// 获取当前类型数据
const fetchCurrentData = async () => {
  const loadingRef = activeTab.value === 'lost' ? lostLoading : foundLoading
  const tableDataRef = activeTab.value === 'lost' ? lostTableData : foundTableData
  const totalRef = activeTab.value === 'lost' ? lostTotal : foundTotal
  const currentPageRef = activeTab.value === 'lost' ? lostCurrentPage : foundCurrentPage
  const pageSizeRef = activeTab.value === 'lost' ? lostPageSize : foundPageSize

  loadingRef.value = true
  tableDataRef.value = [] // 清空旧数据
  
  try {
    // 根据标签页选择不同的API端点
    const apiUrl = activeTab.value === 'lost' 
      ? `${API_BASE_URL}/LostItem/getAllRecord` 
      : `${API_BASE_URL}/FoundItem/getAllRecord`
      
    const response = await axios.get(apiUrl, {
      params: {
        page: currentPageRef.value,
        pageSize: pageSizeRef.value,
        _t: Date.now() // 添加时间戳防止缓存
      },
      headers: {
        'Cache-Control': 'no-cache' // 禁用缓存
      }
    })
    
    if (response.data.code === 200) {
      // 处理数据：统一ID字段并映射时间/地点字段
      const rawData = response.data.data.list || []
      tableDataRef.value = rawData.map(item => {
        const mappedItem = { ...item }
        
        // 统一ID字段
        mappedItem.id = activeTab.value === 'lost' ? item.lostId : item.foundId
        
        // 保留原始时间/地点字段用于详情页
        mappedItem._lostTime = item.lostTime
        mappedItem._foundTime = item.foundTime
        mappedItem._lostLocation = item.lostLocation
        mappedItem._foundLocation = item.foundLocation
        
        return mappedItem
      })
      
      totalRef.value = response.data.data.total || 0
    } else {
      ElMessage.error(response.data.message || '获取数据失败')
    }
  } catch (error) {
    console.error('获取数据失败', error)
    ElMessage.error('网络错误，请稍后再试')
  } finally {
    loadingRef.value = false
  }
}

// 选项卡切换
const handleTabClick = (tab) => {
  activeTab.value = tab.name
  // 重置当前类型的页码
  if (activeTab.value === 'lost') {
    lostCurrentPage.value = 1
  } else {
    foundCurrentPage.value = 1
  }
  fetchCurrentData() // 强制刷新数据
}

// 获取当前选项卡对应时间
const getCurrentTabTime = (row) => {
  return activeTab.value === 'lost' ? row._lostTime : row._foundTime
}

// 获取当前选项卡对应地点
const getCurrentTabLocation = (row) => {
  return activeTab.value === 'lost' ? row._lostLocation : row._foundLocation
}

// 表格选择变化
const handleSelectionChange = (val) => {
  if (activeTab.value === 'lost') {
    lostSelectedRows.value = val
  } else {
    foundSelectedRows.value = val
  }
}

// 显示详情弹窗
const showItemDetail = (item) => {
  // 创建详情内容HTML
  const detailContent = document.createElement('div')
  detailContent.className = 'swal-detail-content'
  
  // 基本信息部分
  const basicInfoHTML = `
    <div class="detail-header">
      <h3>${item.title || '未命名'}</h3>
      <el-tag type="${getStatusTagType(item.status)}">${getStatusText(item.status)}</el-tag>
    </div>
    <div class="detail-body">
      <div class="detail-row">
        <div class="detail-label">ID:</div>
        <div class="detail-value">${item.id || '-'}</div>
      </div>
      <div class="detail-row">
        <div class="detail-label">用户ID:</div>
        <div class="detail-value">${item.userId || '-'}</div>
      </div>
      <div class="detail-row">
        <div class="detail-label">物品类别:</div>
        <div class="detail-value">${getCategoryName(item.categoryId) || '-'}</div>
      </div>
      <div class="detail-row">
        <div class="detail-label">发布时间:</div>
        <div class="detail-value">${formatDateTime(item.createTime) || '-'}</div>
      </div>
      <div class="detail-row">
        <div class="detail-label">${currentTabTimeLabel.value}:</div>
        <div class="detail-value">${formatDateTime(getCurrentTabTime(item)) || '-'}</div>
      </div>
      <div class="detail-row">
        <div class="detail-label">${currentTabLocationLabel.value}:</div>
        <div class="detail-value">${getCurrentTabLocation(item) || '-'}</div>
      </div>
      <div class="detail-row">
        <div class="detail-label">联系方式:</div>
        <div class="detail-value">${item.contactWay || '-'}</div>
      </div>
      <div class="detail-row">
        <div class="detail-label">物品描述:</div>
        <div class="detail-value">${item.description || '无描述'}</div>
      </div>
      
    </div>
  `
  
  // 图片区域
  let imagesHTML = ''
  if (item.images && item.images.length > 0) {
    imagesHTML = `
      <div class="detail-images">
        <h4>物品图片</h4>
        <div class="image-list">
          ${item.images.map(img => `
            <img src="${img.url}" alt="物品图片" 
                 style="width: 120px; height: 120px; margin-right: 10px; margin-bottom: 10px; object-fit: cover">
          `).join('')}
        </div>
      </div>
    `
  }
  
  detailContent.innerHTML = basicInfoHTML + imagesHTML
  
  // 定义弹窗按钮
  const buttons = []
  if (item.status === 1) {
    buttons.push({
      text: '通过审核',
      className: 'swal-button swal-button--success',
      preConfirm: () => handleAudit(item, 'passed')
    })
    
    buttons.push({
      text: '驳回审核',
      className: 'swal-button swal-button--danger',
      preConfirm: () => handleAudit(item, 'rejected')
    })
  }
  
  // 显示弹窗
  Swal.fire({
    title: '信息详情',
    html: detailContent,
    showCancelButton: true,
    cancelButtonText: '关闭',
    confirmButtonText: '确认',
    showLoaderOnConfirm: true,
    focusConfirm: false,
    width: '70%',
    customClass: {
      content: 'swal-custom-content'
    },
    buttonsStyling: false,

    didOpen: () => {
      // 为弹窗内容添加样式
      const style = document.createElement('style')
      style.textContent = `
        .swal-detail-content {
          padding: 20px;
          text-align: left;
        }
        .detail-header {
          display: flex;
          align-items: center;
          margin-bottom: 20px;
        }
        .detail-header h3 {
          margin-right: 15px;
        }
        .detail-row {
          display: flex;
          margin-bottom: 15px;
        }
        .detail-label {
          width: 120px;
          font-weight: bold;
          color: #606266;
        }
        .detail-value {
          flex: 1;
          color: #303133;
        }
        .detail-images {
          margin-top: 20px;
        }
        .image-list {
          display: flex;
          flex-wrap: wrap;
        }
        .swal-custom-content {
          max-height: 80vh;
          overflow-y: auto;
        }
        .swal-button {
          margin: 0 5px;
          padding: 8px 20px;
          border-radius: 4px;
        }
        .swal-button--success {
          background-color: #67c23a;
          color: #fff;
        }
        .swal-button--danger {
          background-color: #f56c6c;
          color: #fff;
        }
      `
      document.head.appendChild(style)
    }
  })
}

// 审核操作
const handleAudit = async (item, status) => {
  try {
    const actionText = status === 'passed' ? '通过' : '驳回'
    
    // 确认操作
    const confirmResult = await Swal.fire({
      title: `确定要${actionText}【${item.title}】的审核吗？`,
      icon: 'warning',
      showCancelButton: true,
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      reverseButtons: true
    })
    
    if (confirmResult.isConfirmed) {
      // 根据当前项类型选择API端点
      const itemType = activeTab.value
      const apiUrl = itemType === 'lost' 
        ? `${API_BASE_URL}/LostItem/${status === 'passed' ? 'approve' : 'reject'}/${item.lostId}` 
        : `${API_BASE_URL}/FoundItem/${status === 'passed' ? 'approve' : 'reject'}/${item.foundId}`
      
      const response = await axios.put(apiUrl)
      
      if (response.data.code === 200) {
        Swal.fire(
          `${actionText}成功`,
          '',
          'success'
        )
        fetchCurrentData()
      } else {
        Swal.fire(
          `${actionText}失败`,
          response.data.message || '操作失败',
          'error'
        )
      }
    }
  } catch (error) {
    console.error('审核操作取消或失败', error)
    Swal.fire(
      '操作失败',
      '网络错误，请稍后再试',
      'error'
    )
  }
}

// 审核通过
const handlePass = async (row) => {
  await handleAudit(row, 'passed')
}

// 审核驳回
const handleReject = async (row) => {
  await handleAudit(row, 'rejected')
}

// 批量通过审核
const handleBatchPass = async () => {
  const selectedRows = getSelectedRows.value
  if (selectedRows.length === 0) {
    ElMessage.warning('请先选择需要审核的记录')
    return
  }
  
  try {
    const confirmResult = await Swal.fire({
      title: `确定要通过选中的${selectedRows.length}条记录的审核吗？`,
      icon: 'warning',
      showCancelButton: true,
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      reverseButtons: true
    })
    
    if (confirmResult.isConfirmed) {
      // 过滤出待审核的记录
      const pendingRows = selectedRows.filter(row => row.status === 1)
      
      if (pendingRows.length === 0) {
        ElMessage.warning('所选记录中没有待审核的记录')
        return
      }
      
      // 根据标签页选择不同的API端点
      const apiUrl = activeTab.value === 'lost' 
        ? `${API_BASE_URL}/lostItem/batchApprove` 
        : `${API_BASE_URL}/foundItem/batchApprove`
      
      const response = await axios.put(apiUrl, {
        // 传递对应类型的ID
        ids: pendingRows.map(row => activeTab.value === 'lost' ? row.lostId : row.foundId)
      })
      
      if (response.data.code === 200) {
        ElMessage.success(`成功通过${response.data.data || 0}条记录的审核`)
        fetchCurrentData()
      } else {
        ElMessage.error(response.data.message || '批量审核失败')
      }
    }
  } catch (error) {
    console.error('批量审核操作取消或失败', error)
  }
}

// 批量驳回审核
const handleBatchReject = async () => {
  const selectedRows = getSelectedRows.value
  if (selectedRows.length === 0) {
    ElMessage.warning('请先选择需要审核的记录')
    return
  }
  
  try {
    const confirmResult = await Swal.fire({
      title: `确定要驳回选中的${selectedRows.length}条记录的审核吗？`,
      icon: 'warning',
      showCancelButton: true,
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      reverseButtons: true
    })
    
    if (confirmResult.isConfirmed) {
      // 过滤出待审核的记录
      const pendingRows = selectedRows.filter(row => row.status === 1)
      
      if (pendingRows.length === 0) {
        ElMessage.warning('所选记录中没有待审核的记录')
        return
      }
      
      // 根据标签页选择不同的API端点
      const apiUrl = activeTab.value === 'lost' 
        ? `${API_BASE_URL}/lostItem/batchReject` 
        : `${API_BASE_URL}/foundItem/batchReject`
      
      const response = await axios.put(apiUrl, {
        // 传递对应类型的ID
        ids: pendingRows.map(row => activeTab.value === 'lost' ? row.lostId : row.foundId)
      })
      
      if (response.data.code === 200) {
        ElMessage.success(`成功驳回${response.data.data || 0}条记录的审核`)
        fetchCurrentData()
      } else {
        ElMessage.error(response.data.message || '批量审核失败')
      }
    }
  } catch (error) {
    console.error('批量审核操作取消或失败', error)
  }
}

// 分页相关
const handleSizeChange = (val) => {
  if (activeTab.value === 'lost') {
    lostPageSize.value = val
  } else {
    foundPageSize.value = val
  }
  fetchCurrentData()
}

const handleCurrentChange = (val) => {
  if (activeTab.value === 'lost') {
    lostCurrentPage.value = val
  } else {
    foundCurrentPage.value = val
  }
  fetchCurrentData()
}

// 辅助方法
const getCategoryName = (categoryId) => {
  const category = categoryList.value.find(c => c.categoryId === categoryId)
  return category ? category.categoryName : '未知分类'
}

const getStatusTagType = (status) => {
  return auditStatusMap[status]?.type || 'default'
}

const getStatusText = (status) => {
  return auditStatusMap[status]?.text || '未知状态'
}

const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  const date = new Date(dateTime)
  return date.toLocaleString()
}

// 处理命令
const handleCommand = (command) => {
  if (command === 'logout') {
    Swal.fire({
      title: '确定要退出登录吗？',
      icon: 'warning',
      showCancelButton: true,
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      reverseButtons: true
    }).then((result) => {
      if (result.isConfirmed) {
        ElMessage.success('退出成功')
        // 实际项目中这里应该有退出登录的逻辑
      }
    })
  }
}
</script>

<style scoped>
/* 样式部分与原代码一致，此处省略 */
.header {
  background-color: #409EFF;
  color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  height: 60px;
}

.logo {
  font-size: 18px;
  font-weight: bold;
}

.user-info {
  display: flex;
  align-items: center;
}

.user-info span {
  margin: 0 10px;
}

.content-wrapper {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.page-title {
  font-size: 22px;
  font-weight: bold;
  margin-bottom: 20px;
}

.table-toolbar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 16px;
}
</style>